package com.vmladenov.cook.core.db;

import java.util.ArrayList;

import com.vmladenov.cook.core.Helpers;
import com.vmladenov.cook.core.RestHelper;
import com.vmladenov.cook.core.db.proxy.BigUsefull;
import com.vmladenov.cook.core.db.proxy.SmallListProxy;
import com.vmladenov.cook.core.html.SmallPreview;
import com.vmladenov.cook.core.objects.UsefulView;

public abstract class WebServiceRepository
{
	protected final String siteUrl = "http://cooking-bg.com/"; 			// "http://10.0.2.2/CookingBg/";     - Emulator
																		// "http://192.168.0.75/CookingBg/"; - Wifi 
																		// "http://cooking-bg.com/";		 - Web

	protected long getUserId()
	{
		return Helpers.getCurrentUser().getId();
	}
	
	protected ArrayList<SmallPreview> convertToSmallPreview(SmallListProxy[] smallListProxies)
	{
		ArrayList<SmallPreview> previews = new ArrayList<SmallPreview>();
		if (smallListProxies != null)
		{
			for (SmallListProxy smallRecipe : smallListProxies)
			{
				SmallPreview preview = new SmallPreview();

				preview.id = smallRecipe.ID;
				preview.title = smallRecipe.Title;
				preview.imageUrl = smallRecipe.SmallImageUrl;
				previews.add(preview);
			}
		}
		return previews;
	}

	protected abstract String getServicePath(); 

	public long getRowCount(String methodName)
	{
		String url = siteUrl + getServicePath() + methodName;
		return RestHelper.GetJSON(url, Long.class);
	}
	
	protected ArrayList<SmallPreview> getPreviews(String methodName, long start, int sorting)
	{
		String url = String.format(siteUrl + getServicePath() + methodName + "?startIndex=%d&count=%d&sorting=%d", start, 20, sorting);
		SmallListProxy[] smallListProxies = RestHelper.GetJSON(url, SmallListProxy[].class);
		return convertToSmallPreview(smallListProxies);
	}
	
	public ArrayList<SmallPreview> searchPreviews(String methodName, String query)
	{
		String url = String.format(siteUrl + getServicePath() + methodName + "?search=%s", query);
		SmallListProxy[] smallListProxies = RestHelper.GetJSON(url, SmallListProxy[].class);
		return convertToSmallPreview(smallListProxies);
	}
	
	
	protected UsefulView getBigUseful(String methodName, long id)
	{
		String url = String.format(siteUrl + getServicePath() + methodName + "?id=%d", id);
		BigUsefull bigUsefull = RestHelper.GetJSON(url, BigUsefull.class);
		return bigUsefull.toUsefulView();
	}
}
